<template>
  <div style="margin-left: 20px">
    <el-form ref="form" label-position="top" :model="serviceObj">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item :label="$t('business.configuration.type')">
            <ko-data-item
              v-model="serviceType"
              itemType="radio"
              :radios="options.service_type_list"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="serviceType !== 'None'" :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('business.workload.annotations')">
            <table style="width: 100%" class="tab-table">
              <tr v-for="(row, index) in annotationList" :key="index">
                <td width="49%">
                  <ko-data-item
                    v-model="row.key"
                    placeholder="e.g. foo"
                    clearable
                    itemType="input"
                  />
                </td>
                <td width="49%">
                  <ko-data-item
                    v-model="row.value"
                    clearable
                    itemType="input"
                  />
                </td>
                <td width="2%">
                  <el-button
                    type="text"
                    style="font-size: 10px"
                    @click="handleAnnotationDelete(index)"
                  >
                    {{ $t("commons.button.delete") }}
                  </el-button>
                </td>
              </tr>
              <tr>
                <td align="left">
                  <el-button @click="handleAnnotationAdd()">{{
                    $t("commons.button.add")
                  }}</el-button>
                </td>
              </tr>
            </table>
          </el-form-item>
        </el-col>
      </el-row>

      <div v-if="hasExternalIP">
        <el-row :gutter="20">
          <table style="width: 100%" class="tab-table">
            <tr>
              <th scope="col" width="20%" align="left">
                <label>{{ $t("business.network.port_name") }}</label>
              </th>
              <th scope="col" width="20%" align="left">
                <label>{{ $t("business.workload.service_port") }}</label>
              </th>
              <th scope="col" width="10%" align="left">
                <label>{{ $t("business.network.protocol") }}</label>
              </th>
              <th scope="col" width="20%" align="left">
                <label>{{ $t("business.workload.container_port") }}</label>
              </th>
              <th scope="col" width="20%" align="left">
                <label>{{ $t("business.workload.node_port") }}</label>
              </th>
              <th />
            </tr>
            <tr v-for="(row, index) in servicePorts" v-bind:key="index">
              <td>
                <ko-data-item v-model="row.name" itemType="input" />
              </td>
              <td>
                <ko-data-item
                  v-model.number="row.port"
                  :placeholder="$t('business.workload.service_port_help')"
                  itemType="number"
                />
              </td>
              <td>
                <ko-data-item
                  v-model="row.protocol"
                  itemType="select"
                  :selections="options.protocol_list"
                />
              </td>
              <td>
                <ko-data-item
                  v-model.number="row.targetPort"
                  :placeholder="$t('business.workload.application_port')"
                  itemType="number"
                />
              </td>
              <th>
                <ko-data-item
                  v-if="serviceType === 'NodePort'"
                  v-model.number="row.nodePort"
                  itemType="number"
                />
              </th>
              <td>
                <el-button
                  type="text"
                  style="font-size: 10px"
                  @click="handlePortDelete(index)"
                  >{{ $t("commons.button.delete") }}</el-button
                >
              </td>
            </tr>
            <tr>
              <td align="left">
                <el-button @click="handlePortAdd">{{
                  $t("commons.button.add")
                }}</el-button>
              </td>
            </tr>
          </table>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="6">
            <el-form-item label="SessionAffinity">
              <ko-data-item
                v-model="serviceObj.spec.sessionAffinity"
                itemType="radio"
                :radios="options.session_type_list"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col
            v-if="serviceObj.spec.sessionAffinity === 'ClientIP'"
            :span="6"
          >
            <el-form-item label="TimeoutSeconds">
              <ko-data-item
                v-model.number="
                  serviceObj.spec.sessionAffinityConfig.clientIP.timeoutSeconds
                "
                itemType="number"
                :dividerName="$t('business.workload.seconds')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <span>{{ $t("business.network.external_ip") }}</span>
            <table style="width: 100%; margin-top: 10px" class="tab-table">
              <tr v-for="(row, index) in externalIps" :key="index">
                <td width="97%">
                  <ko-data-item
                    v-model="row.ip"
                    placeholder="e.g. 1.1.1.1"
                    itemType="input"
                  />
                </td>
                <td>
                  <el-button
                    type="text"
                    style="font-size: 10px"
                    @click="handleExternalIPsDelete(index)"
                  >
                    {{ $t("commons.button.delete") }}
                  </el-button>
                </td>
              </tr>
              <tr>
                <td align="left">
                  <el-button @click="handleExternalIPsAdd"
                    >{{ $t("business.workload.add")
                    }}{{ $t("business.network.external_ip") }}</el-button
                  >
                </td>
              </tr>
            </table>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import {
  Service,
  ServicePort,
  ServiceType
} from "@/views/domain/kubeHud/api/k8s";
import { mergeListToObject, objectToList } from "@/views/domain/kubeHud/utils";
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
// import { parseArryToObj, parseObjToArry } from "@/utils/objArryParse";

const { t } = useI18n();

type Prop = {
  cluster?: string;
};
const props = withDefaults(defineProps<Prop>(), {});
const emit = defineEmits(["save"]);
const serviceObj = defineModel<Service>("serviceObj");

const uiState = reactive({
  loading: false
});

const options = reactive({
  service_type_list: [
    { label: t("business.workload.not_create"), value: "None" },
    { label: "Headless", value: "Headless" },
    { label: "ClusterIP", value: "ClusterIP" },
    { label: "NodePort", value: "NodePort" }
  ],
  session_type_list: [
    { label: "None", value: "None" },
    { label: "ClientIP", value: "ClientIP" }
  ],
  protocol_list: [
    { label: "TCP", value: "TCP" },
    { label: "UDP", value: "UDP" }
  ]
});

// 服务类型
const serviceType = computed<ServiceType>(() => {
  return serviceObj.value?.spec?.type;
});

const isServiceCreated = computed(
  () => serviceType.value && serviceType.value !== "None"
);

const hasExternalIP = computed(() => {
  return serviceType.value === "ClusterIP" || serviceType.value === "NodePort";
});

// 注释,kv列表
const annotationList = ref<{ key: string; value: any }[]>([]);

const externalIps = ref<{ ip: string }[]>([]);

const servicePorts = ref<ServicePort[]>([]);

const handleExternalIPsAdd = () => {
  externalIps.value.push({ ip: "" });
};

const handleExternalIPsDelete = (index: number) => {
  externalIps.value.splice(index, 1);
};

const handleAnnotationAdd = () => {
  annotationList.value.push({ key: "", value: "" });
};

const handleAnnotationDelete = (index: number) => {
  annotationList.value.splice(index, 1);
};

const handlePortAdd = () => {
  servicePorts.value.push({
    name: "",
    port: 0,
    protocol: "TCP",
    targetPort: 0
  });
};

const handlePortDelete = (index: number) => {
  servicePorts.value.splice(index, 1);
};

const parseServiceInfo = (service: Service) => {
  annotationList.value = objectToList(
    service.metadata.annotations,
    "key",
    "value"
  ) as any;
  externalIps.value = service.spec?.externalIPs.map(item => ({
    ip: item
  }));

  servicePorts.value = Object.assign([], service.spec?.ports ?? []);
};

watch(
  () => serviceObj.value,
  (nv, ov) => {
    if (nv != ov) {
      parseServiceInfo(nv);
    }
  }
);

onMounted(() => {
  if (serviceObj.value) {
    parseServiceInfo(serviceObj.value);
  }
});
</script>

<style scoped></style>
